package com.supor.aiot.home.ui.device.config;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.android.baseconfig.common.entity.parameter.ShowDialogParameter;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.helper.NFCHelper;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivityNfcGuideBinding;
import com.supor.aiot.home.helper.DataCache;
import com.supor.aiot.home.utils.HwTouchPop;
import com.supor.aiot.home.utils.PopUtils;
import com.supor.nfc.lib.utils.NfcUtils;

import static com.supor.aiot.common.app.Constants.REQUEST_CODE;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: NFC配网引导页 <br>
 * 作者: lei <br>
 * 日期: 2020/12/8 <br>
 */
public class NFCGuideActivity extends BaseConfigActivity<NoViewModel, ActivityNfcGuideBinding> {
    private AppBasicDialog failureDialog;
    private AppBasicDialog settingDialog;
    String ssid = null;
    String bssid = null;
    String pass = null;
    private String brand = Build.BRAND;
    private RecordBean recordBean;
    private ProductType.ProductModel productModel;
    /**
     * 绑定类型：0-NFC|1-AP|2-NFC AP
     */
    private int configType = 0;

    @Override
    protected int resourceId() {
        return R.layout.activity_nfc_guide;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.configNfc(this);
            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent,
                    null, null);
        }
    }

    @Override
    public void initData() {
        super.initData();
    }

    public void initView() {
        super.initView();
        Intent intent = getIntent();
        if (intent != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
            }
        }

        NfcUtils.init(this);
        PopUtils.getInstance().initNFCPop(this);

        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        /*LinearLayout.LayoutParams llGifLayoutParams =
                (LinearLayout.LayoutParams) bindingView.llGif.getLayoutParams();
        LinearLayout.LayoutParams nfcTipLayoutParams =
                (LinearLayout.LayoutParams) bindingView.llNfcTip.getLayoutParams();
        LinearLayout.LayoutParams touchTipLayoutParams =
                (LinearLayout.LayoutParams) bindingView.tvNfcTouchTip.getLayoutParams();
        if (AppAgent.smallScreen) {
            llGifLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            nfcTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            touchTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_5);
            touchTipLayoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_10);
            bindingView.ivNfcArea.setImageResource(R.mipmap.ic_nfc_area);
        } else {
            llGifLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_17);
            nfcTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_17);
            touchTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_12);
            touchTipLayoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_22);
            bindingView.ivNfcArea.setImageResource(R.mipmap.ic_nfc_area);
        }
        bindingView.llGif.setLayoutParams(llGifLayoutParams);
        bindingView.llNfcTip.setLayoutParams(nfcTipLayoutParams);
        bindingView.tvNfcTouchTip.setLayoutParams(touchTipLayoutParams);*/

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            configType = bundle.getInt(Constants.Key.CONFIG_TYPE, 0);
            ssid = bundle.getString(Constants.Key.SSID);
            bssid = bundle.getString(Constants.Key.BSSID);
            pass = bundle.getString(Constants.Key.PASS);
            Logc.i("NFC ssid= " + ssid + ", bssid= " + bssid + ", pass= " + pass);
        }
        bindingView.toolbar.setLeftText(configType != 0 ? getString(R.string.config_nfc_ap_title) :
                getString(R.string.config_nfc_title));
        bindingView.configTop.setConfig1Text(configType != 0 ? getString(R.string.ap_settings) :
                getString(R.string.bind_config_tip1));

        String tip = getString(R.string.bind_nfc_guide_step2);
        SpannableString ss2 = new SpannableString(tip);

        ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvTextStep2.setText(ss2);

        // 2021/10/14
        /*if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(productModel.modelTypeId)) {
            // gifIv.setImageResource(R.drawable.gif_nfc);

            // 3. 将手机背面NFC位置靠近产品面板的【碰一碰，更多菜】标识区域。
            tip = getString(R.string.bind_nfc_guide_step3);
            SpannableString ss3 = new SpannableString(tip);
            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("碰一碰") - 1, tip.indexOf("碰一碰") + 8,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvTextStep3.setText(ss3);
        } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(productModel.modelTypeId)) {
            // gifIv.setImageResource(R.drawable.gif_nfc_oven);

            // 3. 将手机背面NFC感应区靠近产品面板左侧&#160;&#160;&#160;图标区域。
            tip = getString(R.string.bind_nfc_guide_oven_step3);
            SpannableString ss3 = new SpannableString(tip);
            //拿到所加图片的drawable对象
            Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_nfc_guide_oven, null);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            CenterImageSpan imageSpan = new CenterImageSpan(drawable);
            ss3.setSpan(imageSpan, tip.indexOf("左侧") + 3, tip.indexOf("左侧") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvTextStep3.setText(ss3);
        }*/

        processNFC();
        if (TextUtils.isEmpty(DataCache.GIZ_IP)) {
            DataCache.getGIZIp();
        }
        if ("HUAWEI".equalsIgnoreCase(brand) || "HONOR".equalsIgnoreCase(brand)) {
            HwTouchPop.getInstance().initPop(this);
            bindingView.tvTextStep5.setVisibility(View.VISIBLE);
            bindingView.tvNfcTouchTip.setText(R.string.bind_nfc_area_tip_huawei);
            bindingView.tvTextStep5.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HwTouchPop.getInstance().showPop(NFCGuideActivity.this, bindingView.llRoot);
                }
            });
        } else {
            bindingView.tvTextStep5.setVisibility(View.GONE);
            bindingView.tvNfcTouchTip.setText(R.string.bind_nfc_area_tip);
        }
        bindingView.btnNextStep.setOnClickListener(v -> PopUtils.getInstance().showNFCPop(NFCGuideActivity.this, bindingView.llRoot));
        bindingView.btnCancel.setOnClickListener(v -> finish());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcUtils.mNfcAdapter == null) {
            NfcUtils.init(this);
            NfcUtils.configNfc(this);
        }
        if (!PopUtils.getInstance().isNFCPopShow()) {
            return;
        }
        String gizIp = "";
        if (!TextUtils.isEmpty(DataCache.GIZ_IP)) {
            gizIp = DataCache.GIZ_IP;
            // DataCache.GIZ_IP = BaseSharedPreferences.getString(this, Constants.Key.GIZ_IP);
        }
        recordBean = NFCHelper.getInstance().processIntent(intent);
        if (NFCHelper.getInstance().processRecord(this, intent, recordBean,
                gizIp, ssid, pass, bssid)) {
            DataCache.CONFIG_START_TIME = System.currentTimeMillis();
            PopUtils.getInstance().touchSuccess();
            // SuporPresenter.getInstance().reportGetTinyInfo();
            new Handler().postDelayed(this::jumpToNextActivity, 1700);
        } else {
            PopUtils.getInstance().dismissNFCPop();
        }
        // modify by lei 20220121
        // if (recordBean != null && !TextUtils.isEmpty(recordBean.getProductId())) {
        //     for (ProductType productType : GlobalDataCache.productTypeList) {
        //         for (ProductType.ProductModel child : productType.Children) {
        //             if (!TextUtils.isEmpty(recordBean.getProductId())
        //                     && recordBean.getProductId().equalsIgnoreCase(child.productId)) {
        //                 productModel = child;
        //                 return;
        //             }
        //         }
        //     }
        // }
    }

    @Override
    public <T extends View> T findViewById(int id) {
        if (id == R.id.view_pager && HwTouchPop.getInstance().getPopWindow() != null) {
            return HwTouchPop.getInstance().getPopWindow().findViewById(R.id.view_pager);
        }
        return super.findViewById(id);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    public void updateNFCStatus(int state) {
        super.updateNFCStatus(state);
        NfcUtils.init(this);
        NfcUtils.configNfc(this);
        processNFC();
    }

    private void jumpToNextActivity() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.Key.RECORD_INFO, recordBean);
        bundle.putInt(Constants.Key.CONFIG_TYPE, configType);
        bundle.putString(Constants.Key.SSID, ssid);
        bundle.putString(Constants.Key.BSSID, bssid);
        bundle.putString(Constants.Key.PASS, pass);
        Intent intent = new Intent(this, WifiConfigActivity.class);
        intent.putExtras(bundle);
        intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NfcUtils.mNfcAdapter = null;
        PopUtils.getInstance().dismissNFCPop();
    }

    @Override
    public void onBackPressed() {
        if (HwTouchPop.getInstance().isPopShow()) {
            HwTouchPop.getInstance().dismissPop();
            return;
        }
        if (PopUtils.getInstance().isNFCPopShow()) {
            PopUtils.getInstance().dismissNFCPop();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Constants.REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }

    protected void processNFC() {
        if (NfcUtils.NFC_STATE == 2) {
            showNFCDialog();
        } else {
            closeNFCDialog();
        }
    }

    private void showNFCDialog() {
        if (settingDialog != null) {
            if (settingDialog.isShowing()) {
                return;
            } else {
                settingDialog.show();
            }
            return;
        }
        ShowDialogParameter parameter = new ShowDialogParameter()
                .setTitle(getString(com.supor.aiot.common.R.string.nfc_close))
                .setMsg(getString(com.supor.aiot.common.R.string.nfc_setting_tip))
                .setStrYes(getString(com.supor.aiot.common.R.string.setting))
                .setStrNo(getString(com.supor.aiot.common.R.string.cancel));
        settingDialog = DialogUtils.opDialog(this, parameter,
                (dialog, which) -> startActivity(new Intent(Settings.ACTION_NFC_SETTINGS)),
                (dialog, which) -> {
                    dialog.cancel();
                    finish();
                });
        settingDialog.show();
    }

    private void closeNFCDialog() {
        if (settingDialog != null && settingDialog.isShowing()) {
            settingDialog.dismiss();
        }
    }
}
